<template>

  <div class="new-page">
    <draggable
      class="h-100 d-flex flex-column"
      :group="{ name: 'people' }"
      filter=".undraggable"
    >

      <div class="pp-t-96 undraggable p16-a">
        <div class="p-vm-btn-box undraggable">
          <a-button ghost type="primary" @click="saveDraft">
            保存草稿
          </a-button>
          <a-button type="primary" class="ml-8" :disabled="flag===1" :loading="updateRepReportTemplateLoading" @click="update">
            保存修改
          </a-button>
          <a-button type="primary" class="ml-8" :loading="addRepReportTemplateLoading" @click="addVisible=true">
            发布新版本
          </a-button>
        </div>
        <div class="text-color-21252e">
          模版管理
        </div>
        <a-row>
          <a-col :span="20">
            <a-row :gutter="8">
              <a-col :span="8">
                <span class="text-color-505363 fs-12">模板名称：</span>
                <span class="text-color-505363 fs-12">{{ rowHis.reportName }}</span>
              </a-col>
              <a-col :span="8">
                <span class="text-color-505363 fs-12">模板状态：</span>
                <span class="text-color-505363 fs-12">{{ rowHis.enable===1?"启用":'禁用' }}</span>
              </a-col>
              <a-col :span="8">
                <span class="text-color-505363 fs-12">所属一级分类：</span>
                <span class="text-color-505363 fs-12">{{ rowHis.smi||'--' }}</span>
              </a-col>
              <a-col :span="8">
                <span class="text-color-505363 fs-12  jwhxz-lable">机号限制：</span>
                <span class="text-color-505363 fs-12 jwhxz-box">{{ tailnumbers||'--' }}</span>
              </a-col>

              <a-col :span="8">
                <span class="text-color-505363 fs-12  jwhxz-lable">描述：</span>
                <span class="text-color-505363 fs-12  jwhxz-box">{{ rowHis.description||'--' }}</span>
              </a-col>
              <a-col :span="8">
                <span class="text-color-505363 fs-12">所属二级分类：</span>
                <span class="text-color-505363 fs-12">{{ rowHis.imi||'--' }}</span>
              </a-col>
            </a-row>
          </a-col>
        </a-row>
      </div>
      <div id="vm-pp-t-96" class="pp-rb-box version-management undraggable">
        <a-row class="flex-1 of-h coding-desgin-main-box">
          <!-- 标签 -->
          <a-col :span="4" class=" vm-tabs-main decoding-box-item decoding-box-item-3">

            <a-tabs :active-key="flag" :animated="false" class="d-flex flex-column" @change="changeFlag">
              <a-tab-pane :key="1" tab="草稿">
                <div
                  v-for="(item,index) in draftData"
                  :key="item.id+index"
                  :class="['his-item-box text-over',index===draftAc?'his-item-box-ac':'']"
                  class="his-item-box fs-12"
                  @click="draftClick(index)"
                >
                  {{ item.version }}

                  <a-dropdown placement="bottomRight">
                    <a-menu slot="overlay">
                      <a-menu-item>
                        <a @click="delItemHandler(item)">删除</a>
                      </a-menu-item>

                    </a-menu>
                    <a-icon :component="require('@/assets/icon/More_vertical.svg')" class="export-more" />
                  </a-dropdown>
                </div>
              </a-tab-pane>
              <a-tab-pane :key="2" tab="历史版本">
                <div
                  v-for="(item,index) in versionList"
                  :key="item+index"
                  :class="['his-item-box text-over',index===hisNameAc?'his-item-box-ac':'']"
                  class="his-item-box fs-12"
                  @click="hisClick(index)"
                >
                  {{ item.version }}
                  <!-- <a-popconfirm
                    title="确认删除此项?"
                    ok-type="danger"
                    ok-text="确认"
                    placement="bottom"
                    cancel-text="取消"
                    @confirm="delItemHandler(item)"
                  >
                    <a-icon :component="require('@/assets/icon/close.svg')" />
                  </a-popconfirm> -->

                  <a-dropdown placement="bottomRight">
                    <a-menu slot="overlay">
                      <a-menu-item>
                        <a @click="delItemHandler(item)">删除</a>
                      </a-menu-item>

                    </a-menu>
                    <a-icon :component="require('@/assets/icon/More_vertical.svg')" class="export-more" />
                  </a-dropdown>
                </div>
              </a-tab-pane>
            </a-tabs>
            <a-tabs default-active-key="1" :animated="false" class="d-flex flex-column vm-label-tabs">
              <a-tab-pane key="1" tab="默认参数标签">
                <VueTree :tree-data="labelTree" :clone-dog="cloneDog" name-key="name" children-key="children" />
              </a-tab-pane>
              <a-tab-pane key="2" tab="特殊参数标签">
                <VueTree :tree-data="showSystemLabel" :clone-dog="cloneDog" name-key="labelName" children-key="children" />
                <!-- <a-input-search style="margin-bottom: 8px" placeholder="查询特殊参数标签" @click="focusSearch" @change="onSChange" /> -->
                <!-- <draggable
                  class="d-flex flex-column"
                  :list="showSystemLabel"
                  :group="{ name: 'people', pull: 'clone', put: false }"
                  :clone="cloneDog"
                >
                  <div
                    v-for="item in showSystemLabel"
                    :key="item.id"
                    class="draggable"
                  >
                    {{ item.label_name }}
                  </div>
                </draggable> -->
              </a-tab-pane>
            </a-tabs>
          </a-col>

          <!-- 设计 -->
          <div class="coding-design-box">
            <div>
              <a-tabs v-model="showDcodeDesign" @change="changeShowDcodeDesign">
                <a-tab-pane :key="1">
                  <div slot="tab">
                    <span>解码设计</span>
                    <a-tooltip placement="topLeft">
                      <template slot="title">
                        <span>勾选展示格式化占位符</span>
                      </template>
                      <a-checkbox :checked="displayFormat[1]" style="margin-left:4px" @click="clickTab" @change="displayFormat[1]=!displayFormat[1]" />
                    </a-tooltip>

                  </div>
                </a-tab-pane>
                <a-tab-pane :key="2">
                  <div slot="tab">
                    <span>显示设计</span>
                    <a-tooltip placement="topLeft">
                      <template slot="title">
                        <span>勾选展示格式化占位符</span>
                      </template>
                      <a-checkbox :checked="displayFormat[2]" style="margin-left:4px" @click="clickTab" @change="displayFormat[2]=!displayFormat[2]" />
                    </a-tooltip>

                  </div>
                </a-tab-pane>
              </a-tabs>
            </div>
            <a-spin :spinning="repReportVersionLoading">
              <a-col :span="24" class="h-100 decoding-box-item code-tmp-1 pl-10 pr-10">

                <table id="myTable" border="1">
                  <thead>
                    <tr>
                      <th class="vm-th" width="13" />
                      <th
                        v-for="(item,index) in colMax"
                        :key="item"
                        :class="[index===0||(index+1)%5===0?'vm-th-im':'']"
                        class="vm-th"
                        width="13"
                      >{{ item }}</th>
                    </tr>
                  </thead>

                  <tbody>
                    <tr v-for="item in maxRow" :key="item" class="vm-tr">
                      <td class="vm-td">{{ item+1 }}</td>

                    </tr>
                  </tbody>
                </table>
                <RecycleScroller
                  :items="maxRow"
                  :item-size="60"
                >

                  <template slot-scope="{ item }">

                    <draggable
                      class="h-100 d-flex-i-f ai-end vm-td-div"
                      :list="objData[item+1]||[]"
                      :group="{ name: 'people' }"
                      @change="(e)=>log(e,item+1)"
                    >
                      <template v-for="(item2,index) in (objData[item+1]?objData[item+1]:[])">
                        <div
                          :key="item2.id+''+index"
                          :class="['list-group-item',item2.group_name==='system'?'vm-label-span-box':'']"
                          :title="item2.value?item2.value:!displayFormat[showDcodeDesign]?item2.label_name:item2.display_format"
                          :style="{'width':`${13*(item2.width||1)-4}px`}"
                        >
                          <template v-if="item2.value">
                            <span v-if="item2.group_name!=='system'" :title="item2.value">{{ item2.value }}</span>
                            <span v-else class="vm-label-span" :title="item2.value">{{ item2.value }}</span>
                          </template>
                          <template v-if="!item2.value&&!displayFormat[showDcodeDesign]">
                            <template v-if="item2.label_name">
                              <span v-if="item2.group_name!=='system'" :title="item2.label_name">{{ item2.label_name }}</span>
                              <span v-else class="vm-label-span" :title="item2.label_name">{{ item2.label_name }}</span>
                            </template>
                            <template v-else>
                              <span v-if="item2.group_name!=='system'" :title="item2.display_format">{{ item2.display_format }}</span>
                              <span v-else class="vm-label-span" :title="item2.display_format">{{ item2.display_format }}</span>
                            </template>

                          </template>
                          <template v-if="!item2.value&&displayFormat[showDcodeDesign]">
                            <span v-if="item2.group_name!=='system'" :title="item2.display_format">{{ item2.display_format }}</span>
                            <span v-else class="vm-label-span" :title="item2.display_format">{{ item2.display_format }}</span>
                          </template>
                        </div>
                      </template>

                    </draggable>

                  </template>

                </RecycleScroller>

              </a-col>

            </a-spin>
          </div>

        </a-row>
      </div>
    </draggable>

    <a-modal
      v-model="addVisible"
      :mask-closable="false"
      title=""
      :width="330"
      :dialog-style="{height:'350px'}"
      class="rt-i-modal"
      centered
      :confirm-loading="addRepReportTemplateLoading"
      @ok="insert"
      @cancel="cancelHandler"
    >
      <span slot="closeIcon" class="c-dialog-close-icon"><a-icon :component="require('@/assets/icon/close.svg')" /></span>

      <div class="c-dialog-title fw-500">填写版本号</div>
      <a-form-model
        ref="addForm"
        :model="addForm"
        :rules="addRules"
        layout="horizontal"
      >

        <a-form-model-item label="版本号" prop="version">
          <a-input v-model="addForm.version" placeholder="版本号" class="input-type-o" style="width: 100%" />
        </a-form-model-item>
        <a-form-model-item label="生效时间" prop="effectTime">
          <a-date-picker
            v-model="addForm.effectTime"
            style="width: 100%;min-width: 100%;"
            format="YYYY-MM-DD HH:mm:ss"
            class="input-type-o"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="生效时间"
            show-time
          />
        </a-form-model-item>
        <!-- <a-form-model-item label="级别" prop="level">
          <a-select
            v-model="addForm.level"
            style="minWidth: 130px"
            placeholder="请选择"
            allow-clear
          >
            <a-select-option v-for="selectItem in priorityList" :key="selectItem.id" :value="selectItem.value">
              {{ selectItem.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item> -->

      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import draggable from 'vuedraggable';
import { mapActions, mapState } from 'vuex';
import { RecycleScroller } from 'vue-virtual-scroller';
import VueTree from './components/vueTree';
const codeTmpHandler1 = function() {
  const scollTop = this.scrollTop;
  const scollLeft = this.scrollLeft;
  document.querySelector('.code-tmp-1 tbody').style.transform = `translateY(-${scollTop}px)`;
  document.querySelector('.code-tmp-1 thead').style.transform = `translateX(-${scollLeft}px)`;
};

export default {
  components: {
    draggable,
    RecycleScroller,
    VueTree
  },
  data() {
    return {
      treeData: [
        {
          name: 'test1',
          id: '1',
          children: [
            {
              name: 'test1-1',
              id: '1-1'
            }
          ]
        },
        {
          name: 'test2',
          id: '2'

        }
      ],
      addVisible: false,
      addForm: {
        version: ''
      },
      addRules: Object.freeze({
        version: [
          { required: true, message: '请填写版本号', trigger: 'change' }
        ],
        effectTime: [
          { required: true, message: '请填写生效时间', trigger: 'change' }
        ]

        // relatedCode: [
        //   { required: true, type: 'array', message: '请选择', trigger: 'change' }
        // ]
      }),
      displayFormat: {
        1: false,
        2: false
      },
      showDcodeDesign: 1,
      showSystemLabel: [],
      showNormalLabel: [],
      systemLabel: [],
      normalLabel: [],
      showNormalList: [],
      draftAc: 0,
      renderData: [],
      draftData: [],
      flag: 2,
      hisNameAc: 0,

      objData: {},
      repData: [],
      // x轴排序可能有空缺
      rowNums: [],
      // x轴排序  填满空缺
      maxRow: [],
      // 最多列
      colMax: 0,
      rowHis: []
    };
  },
  computed: {
    ...mapState('templateManagement', [
      'repReportVersionData',
      'repReportVersionLoading',
      'addRepReportTemplateLoading',
      'updateRepReportTemplateLoading',
      'versionList',
      'labelTree'
    ]),
    tailnumbers() {
      if (Object.prototype.toString.call(this.rowHis.tailnumber) === '[object Array]') {
        return this.rowHis.tailnumber.join();
      } else {
        return this.rowHis.tailnumber;
      }
    }
    // rowHis() {
    //   return this.renderData[this.flag === 1 ? this.draftAc : 0] ?? [];
    // },
    // rowNums() {
    //   return [...new Set(this.rowHis?.templateDetails?.flatMap(item => item.row) ?? [])].sort((a, b) => a - b);
    // },

    // maxRow() {
    //   const rowTotal = Math.max(0, ...this.rowNums ?? []);
    //   const row = [];
    //   for (let i = 0; i < rowTotal; i++) {
    //     row.push(i);
    //   }

    //   return row;
    // },

    // colMax() {
    //   return Math.max(0, ...Object.values(this.rowTotalAll?.obj));
    // },

    // rowTotalAll() {
    //   const obj = {};
    //   const objData = {};
    //   for (const item of this.rowNums) {
    //     const rowLite = this.rowHis?.templateDetails?.filter(item2 => item2.row === item);
    //     objData[item] = rowLite;
    //     const t = rowLite.reduce((a, b) => {
    //       return a + b?.width ?? 0;
    //     }, 0);

    //     obj[item] = t;
    //   }

    //   return { obj, objData };
    // }
  },
  async mounted() {
    this.hisNameAc = 0;
    this.draftAc = 0;
    this.changeShowDcodeDesign();
    const { smi, imi } = this.$route.query;
    this.getLabelParameters({ smi, imi });
    // .then(rep => {
    //   rep.data.sort((a, b) => a.labelName.localeCompare(b.labelName));
    //   const normalLabel = rep.data.filter(item => item.groupName !== 'system') ?? [];
    //   const systemLabel = rep.data.filter(item => item.groupName === 'system') ?? [];

    //   this.normalLabel = normalLabel;
    //   this.showNormalLabel = this.createTree(normalLabel);
    //   this.systemLabel = systemLabel;
    //   this.showSystemLabel = this.createTree(systemLabel);
    // });

    const table = document.querySelector('.code-tmp-1 .vue-recycle-scroller');

    table.addEventListener('scroll', codeTmpHandler1);
  },
  methods: {
    ...mapActions('templateManagement', [
      'getTemplateManagement',
      'insertRepReportTemplate',
      'updateRepReportTemplate',
      'getLabelParameters',
      'deleteVM',
      'getVersion'
    ]),
    async getTM(params = this.$route.query) {
      await this.getTemplateManagement({ ...params, templateType: this.showDcodeDesign });

      this.flag = 2;
      this.renderData = this.repReportVersionData;

      this.draftAc = 0;
    },
    createTree(nodes) {
      var newNodes = {};
      nodes.map(function(cur, i, arr) {
        newNodes[cur.id] = cur;
      });

      var list = [];
      for (var i = 0; i < nodes.length; i++) {
        var parent = newNodes[nodes[i].pid];
        if (parent) {
          ((parent['children']) || (parent['children'] = [])).push(nodes[i]);
        } else {
          list.push(nodes[i]);
        }
      }
      return list;
    },
    renderTable(flag = false, newLine = 0) {
      this.rowHis = this.renderData[this.flag === 1 ? this.draftAc : 0] ?? [];
      this.rowNums = [...new Set(this.rowHis?.templateDetails?.flatMap(item => +item.row) ?? [])].sort((a, b) => a - b);

      const rowTotal = Math.max(0, ...this.rowNums ?? []) + 1 + newLine;
      const row = [];
      for (let i = 0; i < rowTotal; i++) {
        row.push(i);
      }

      this.maxRow = row;

      const colObj = {};
      for (const item of this.rowNums) {
        const rowLite = this.rowHis?.templateDetails?.filter(item2 => item2.row === item);
        const t = rowLite.reduce((a, b) => {
          return a + b?.width ?? 0;
        }, 0);

        colObj[item] = t;
      }

      if (!flag) {
        this.colMax = Math.max(0, ...Object.values(colObj)) + 10;
      }
    },
    setCurrenData() {
      const objData = {};
      for (const item of this.rowNums) {
        const rowLite = this.rowHis?.templateDetails?.filter(item2 => +item2.row === +item);
        objData[item] = rowLite;
      }
      this.objData = objData;

      this.$nextTick(() => {
        const thw = document.querySelector('.code-tmp-1 thead').clientWidth;
        const iw = document.querySelector('.code-tmp-1 .vue-recycle-scroller__item-wrapper');

        iw.style.width = `${thw - 24}px`;
      });
    },
    // 切换解码和显示
    async changeShowDcodeDesign() {
      this.renderData = [];
      await this.getVersion({ templateName: this.$route.query.templateName, templateType: this.showDcodeDesign });
      const versionIdIndex = this.versionList.findIndex(item => item.version === this.$route.query.version) > 0 ? this.versionList.findIndex(item => item.version === this.$route.query.version) : 0;

      this.hisNameAc = versionIdIndex;
      const versionItem = this.versionList?.[this.hisNameAc];
      if (versionItem?.version) {
        await this.getTM({ ...this.$route.query, version: versionItem.version, id: versionItem.id });
      }

      this.renderTable();
      this.setCurrenData();
    },

    focusSearch(e) {
      e.target.focus();
    },
    log3(evt, a, b) {
      // console.log(evt, a, b);
    },
    log: function(evt, rowIndex) {
      console.log(evt);
      const type = Object.keys(evt)[0];
      if (type === 'moved') {
        const { newIndex, oldIndex, element } = evt.moved;
        if (newIndex < oldIndex) {
          const difN = oldIndex - newIndex;
          for (let i = 1; i <= difN; i++) {
            const index = newIndex + i;
            this.objData[element.row][index].col += 1;
          }
        } else {
          const difN = newIndex - oldIndex;
          for (let i = 0; i < difN; i++) {
            const index = oldIndex + i;
            this.objData[element.row][index].col -= 1;
          }
        }
        element.col = newIndex;
      } else if (type === 'added') {
        const { newIndex, element } = evt.added;
        element.row = rowIndex;
        element.col = newIndex;
        this.objData[rowIndex] ? this.objData[rowIndex] : this.$set(this.objData, rowIndex, []);
        this.objData[rowIndex][newIndex] = element;
        this.objData[rowIndex].forEach((element, index) => {
          if (index > newIndex) {
            element.col += 1;
          }
        });
        const t = this.objData[rowIndex].reduce((a, b) => {
          return a + b?.width ?? 0;
        }, 0);
        this.rowHis?.templateDetails.push(element);
        this.renderTable(true);
        this.colMax = Math.max(this.colMax, t);
      } else if (type === 'removed') {
        const { oldIndex } = evt.removed;

        this.objData[rowIndex].forEach((element, index) => {
          if (index >= oldIndex) {
            element.col -= 1;
          }
        });
      }
      this.$nextTick(() => {
        const thw = document.querySelector('.code-tmp-1 thead').clientWidth;
        const iw = document.querySelector('.code-tmp-1 .vue-recycle-scroller__item-wrapper');

        iw.style.width = `${thw - 24}px`;
      });
    },
    clickTab(e) {
      e.stopPropagation();
    },
    changeFlag(v) {
      if (+v === 1) {
        this.draftData = localStorage.getItem(`draft${this.$route.query.id}${this.showDcodeDesign}`) ? JSON.parse(localStorage.getItem(`draft${this.$route.query.id}${this.showDcodeDesign}`)) : [];
        this.renderData = this.draftData;
        this.flag = 1;
        if (this.draftData?.length > 0) {
          this.draftClick(0);
        }
      } else {
        this.renderData = this.repReportVersionData;
        this.flag = 2;
        if (this.repReportVersionData?.length > 0) {
          this.hisClick(0);
        }
      }
    },
    insert() {
      //  {row: 1, col: 0, original_col: 1, display_format: "<401>GE", text_type: 2, width: 7}
      //  {row: 1, col: 0, original_col: 1, display_format: "<401>GE", text_type: 2, width: 7, value: "<401>GE"}
      this.$refs.addForm.validate(valid => {
        if (valid) {
          const params = {
            ...this.rowHis,
            templateDetails: Object.values(this.objData).flat(),
            id: undefined,
            version: this.addForm.version
          };
          for (const key in params) {
            if (Object.hasOwnProperty.call(params, key)) {
              const element = params[key];
              if (Object.prototype.toString.call(element) === '[object Null]') {
                params[key] = '';
              }
            }
          }
          params.tailnumber === '' ? params.tailnumber = [] : '';
          this.insertRepReportTemplate(params).then(res => {
            if (res) {
              this.hisNameAc = 0;
              this.getVersion({ templateName: this.$route.query.templateName, templateType: this.showDcodeDesign });
              this.cancelHandler();
            }
          });
        } else {
          return false;
        }
      });
    },

    update() {
      const params = {
        ...this.rowHis,
        templateDetails: Object.values(this.objData).flat()
      };
      for (const key in params) {
        if (Object.hasOwnProperty.call(params, key)) {
          const element = params[key];
          if (Object.prototype.toString.call(element) === '[object Null]') {
            params[key] = '';
          }
        }
      }
      params.tailnumber === '' ? params.tailnumber = [] : '';
      this.updateRepReportTemplate(params);
    },
    saveDraft() {
      const params = {
        ...this.rowHis,
        templateDetails: Object.values(this.objData).flat(),
        version: (this.rowHis.version.split('-')[0] ?? '0') + '-' + this.$moment.utc(new Date()).format('YYYYMMDDHHmmss')
      };
      const t = localStorage.getItem(`draft${this.$route.query.id}${this.showDcodeDesign}`) ? JSON.parse(localStorage.getItem(`draft${this.$route.query.id}${this.showDcodeDesign}`)) : [];

      t.push(params);
      this.draftData = t;
      this.renderData = this.draftData;
      localStorage.setItem(`draft${this.$route.query.id}${this.showDcodeDesign}`, JSON.stringify(t));
      this.draftAc = this.renderData.length - 1;
      this.$message.success('保存成功');
    },
    draftClick(index) {
      this.draftAc = +index;
      this.renderTable();
      this.setCurrenData();
    },
    async hisClick(index) {
      this.hisNameAc = +index;
      const versionItem = this.versionList?.[index];
      await this.getTM({ ...this.$route.query, version: versionItem.version, id: versionItem.id });
      this.renderTable();
      this.setCurrenData();
    },
    // onSChange(e) {
    //   const value = e.target.value.toUpperCase();
    //   const list = this.systemLabel
    //     .map(item => {
    //       if (item.label_name.indexOf(value) > -1) {
    //         return item;
    //       }
    //     }).filter((item, i, self) => item && self.indexOf(item) === i);
    //   this.showSystemLabel = list;
    // },
    // onChange(e) {
    //   const value = e.target.value.toUpperCase();
    //   const list = this.normalLabel
    //     .map(item => {
    //       if (item.label_name.indexOf(value) > -1) {
    //         return item;
    //       }
    //     }).filter((item, i, self) => item && self.indexOf(item) === i);
    //   this.showNormalLabel = list;
    // },
    delItemHandler(item) {
      if (this.flag === 1) {
        this.draftData.splice(this.draftAc, 1);
        localStorage.setItem(`draft${this.$route.query.id}${this.showDcodeDesign}`, JSON.stringify(this.draftData));
        this.draftData = localStorage.getItem(`draft${this.$route.query.id}${this.showDcodeDesign}`) ? JSON.parse(localStorage.getItem(`draft${this.$route.query.id}${this.showDcodeDesign}`)) : [];
        this.draftClick(0);
      } else {
        this.deleteVM({ id: item.id, version: item.version }).then(async res => {
          if (res) {
            this.changeShowDcodeDesign();
          }
        });
      }
    },
    cancelHandler() {
      this.addVisible = false;
      this.addForm.version = '';
      this.$refs.addForm?.resetFields();
    },
    cloneDog(tagItem) {
      const item = {
        ...tagItem

      };
      return item;
    }
  }
};
</script>

<style lang="less" >
@import './versionManagement.less';
</style>
